package com.wyy.multiredis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurationImportFilter;
import org.springframework.boot.autoconfigure.AutoConfigurationMetadata;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import java.util.Arrays;
import java.util.List;

/**
 * @Date: 2023/12/20
 * @Author: wyy
 */

@AutoConfiguration
public class ExcludeDefaultRedisConfiguration implements AutoConfigurationImportFilter, EnvironmentAware {
    private final Logger log = LoggerFactory.getLogger(getClass());
    private final String excludeKey = "spring.redis.exclude.default";
    private final List<String> EXCLUDE_AUTO_CONFIGURATION_CLASSES =
            Arrays.asList(RedisAutoConfiguration.class.getName(), RedisReactiveAutoConfiguration.class.getName());


    private Environment environment;

    @Override
    public boolean[] match(String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) {
        boolean[] res = new boolean[autoConfigurationClasses.length];
        boolean excludedDefaultRedisConfiguration = excludeDefaultRedisConfiguration(environment);
        for (int i = 0; i < autoConfigurationClasses.length; i++) {
            if (excludedDefaultRedisConfiguration
                    && autoConfigurationClasses[i] != null
                    && EXCLUDE_AUTO_CONFIGURATION_CLASSES.contains(autoConfigurationClasses[i])) {
                log.info("exclude auto configuration:{}", autoConfigurationClasses[i]);
                res[i] = false;
            } else {
                res[i] = true;
            }
        }
        return res;
    }

    private boolean excludeDefaultRedisConfiguration(Environment environment) {
        return Binder.get(environment).bind(excludeKey, Boolean.class).orElseGet(() -> true);
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
